package system

import (
	"mytest/initialize"
	"mytest/models"
	"mytest/models/request"

	"gorm.io/gorm"
)

// 获取 所有的api列表
func GetApiList(db *gorm.DB, req request.MenuList) (error, []models.SysApis, int64) {
	db = db.Model(models.SysApis{})
	var count int64
	err := db.Count(&count).Error
	if err != nil {
		return err, nil, 0
	}

	var apis []models.SysApis
	if req.Desc {
		err := db.Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Order(req.OrderKey).Preload("Parameters").Find(&apis).Error
		if err != nil {
			return err, nil, 0
		}
	} else {
		err := db.Offset((req.Page - 1) * req.PageSize).Limit(req.PageSize).Preload("Parameters").Find(&apis).Error
		if err != nil {
			return err, nil, 0
		}
	}
	return nil, apis, count
}

// 添加一个已经开发的api记录
func CreateApi(db *gorm.DB, api *models.SysApis) error {
	return db.Create(api).Error
}

// 删除一个api记录
func DeleteApi(db *gorm.DB, id int) error {
	tmpdb := db.Delete(&models.SysApis{}, id)
	if tmpdb.RowsAffected == 0 {
		return initialize.ErrNoRowsAffected
	}
	return nil
}
